class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
    }
    // 得到外贸箱单主表数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['billNo'] = $.trim($("#BillNo").val());                                 // 外贸箱单号（自动生成）
        item['doHeaderId'] = $.trim($("#DoHeaderId").val());                         // 发货发令单标识
        item['styleNo'] = $.trim($("#StyleNo").val());                               //  
        item['garmentFactoryId'] = $.trim($("#GarmentFactoryId").val());             //   
        item['dateOfDelivery'] = $.trim($("#DateOfDelivery").val());                 // 日期
        item['grossWeight'] = $.trim($("#GrossWeight").val());                       // 
        item['netWeight'] = $.trim($("#NetWeight").val());                           // 
        item['cubage'] = $.trim($("#Cubage").val());                                 // 体积
        item['inCase'] = $.trim($("#InCase").val());                                 // 箱装
        item['description'] = formatNullInputValue($.trim($("#Description").val())); // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#BillNo").val(item.billNo);
        $("#DateOfDelivery").val(item.dateOfDelivery);
        $("#DoHeaderId").val(item.doHeaderId);
        $("#StyleNo").empty();
        $("#StyleNo").append('<option value="' + item.styleNo + '">' + item.styleNo + '</option>');
        $("#DoBillNo").val(item.doBillNo);
        $("#SoNo").val(item.soNo);
        $("#CustomerName").val(item.customerName);
        $("#GarmentFactoryId").val(item.garmentFactoryId);
        $("#GarmentFactoryName").val(item.garmentFactoryName);
        $("#Destination").val(item.destination);
        $("#ShippingTypeName").val(item.shippingTypeName);
        $("#DutyManName").val(item.dutyManName);
        $("#NoOfContract").val(item.noOfContract);
        $("#GrossWeight").val(item.grossWeight);
        $("#NetWeight").val(item.netWeight);
        $("#Cubage").val(item.cubage);
        $("#InCase").val(item.inCase);
        $("#Description").val(item.description);
        $("#UpdatedBy").val(item.updatedBy);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(item.updatedDate);
        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LinesList);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLines.AutoAdjustTableHeightForLines();
        });
        $("#BillNo").focus();
    }
    Save() {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageSstatus) === 1) {
                    $("#HeaderId").val(data);   // 设置刚才插入的记录ID
                    $self.dataId = data;
                    $("#menu_02").show();
                    $("#menu_03").show();
                }
            }
        });
    }
    New() {
        super.New();
        this.FetchNewBillNo();
        $("#StyleNo").empty();
        $("#tabData21 tbody").empty();
        $("#tabData31 tbody").empty();
        $("#ButSaveLines").show();
        $("#menu_02").hide();
        $("#menu_03").hide();
        $("#BillNo").focus();
    }
    FetchNewBillNo() {
        super.DoAjax(null, "/trade/packing_list/header/fetchNewBillNo.html", function (data, $self) {
            $("#BillNo").val(data.BillNo);
        });
    }
    DoChoiceDo() {
        let _choice = new CommonChoice();
        _choice.DoChoiceDo(0, '选择发货发令单', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#DoBillNo").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }

                $("#DoHeaderId").val(data[0]);
                $("#DoBillNo").val(data[1]);
                $("#CustomerName").val(data[2]);
                $("#DateOfDelivery").val(data[3]);
                $("#Destination").val(data[4]);
                $("#ShippingTypeName").val(data[5]);
                $("#DutyManName").val(data[6]);
                // 设置款号
                super.DoAjax(parseInt($("#DoHeaderId").val()), "/trade/delivery_command_sheet/header/fetchStyleNoByHeaderKey.html", function (data, $self) {
                    if (data !== null && data.length !== 0) {
                        $("#StyleNo").empty();
                        let options = [];
                        options.push('<option value="-1">-- 请选择 --</option>');
                        for (let i = 0; i < data.length; i++) {
                            options.push('<option value="', data[i], '">', data[i], '</option>');
                        }
                        $("#StyleNo").html(options.join(''));
                    } else {
                        ShowErrorMessagePanel('该发货发令单没有款号信息。');
                    }
                });
            }
        });
    }
    DoChoiceGarmentFactory() {
        let _choice = new CommonChoice();
        _choice.DoChoiceSupplier(0, '选择加工厂', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#GarmentFactoryName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#GarmentFactoryId").val(data[0]);
                $("#GarmentFactoryName").val(data[1]);
                $("#GarmentFactoryName").focus();
            }
        });
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        $("Button.act__save").hide();
        $("span.act__delete").removeClass("trash");
        $("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.$input = null;
    }
    BuildDataTable(result) {
        $('#tabData31 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            this.rows = 0;
            // 自适应高度
            _InstancePageLines.AutoAdjustTableHeightForLines();
            return false;
        }
        let content_01 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].linesId + '">';
            content_01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].startNo) + '</td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].endNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].productName) + '</td>';
            content_01 += '<td _mash_colour_id="' + result[i].colourId + '">' + formatNullData(result[i].colourName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].suitSizeName) + '</td>';
            content_01 += '<td class="edited-cell">' + formatNullData(result[i].inBox) + '</td>';
            content_01 += '<td>' + result[i].inCase + '</td>';
            content_01 += '<td>' + formatNullData(result[i].shippingMarkNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].description) + '</td>';
            content_01 += '</tr>';

            $('#tabData31 tbody').append(content_01);
            content_01 = '';
        }
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let _cellid = "_cell__field";
        let _cellname = "__cell__field";
        $('#tabData31 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), _cellid, _cellname, 0);
        });

        setOneTableRowColor("tabData31");
    }
    GetLinesData() {
        let jsonResult = {};
        let insertList = [];
        let updateList = [];
        //得到修改过数据
        $('#tabData31 tbody').find("tr").each(function () {
            let $tr1 = $(this);
            if ($tr1.find("td.dirty").length) {
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['billNo'] = $("#BillNo").val();
                item['linesId'] = $tr1.attr("_mash_id");
                item['startNo'] = $.trim($tr1.find('td').eq(1).text());
                item['endNo'] = $.trim($tr1.find('td').eq(2).text());
                item['styleNo'] = $.trim($tr1.find('td').eq(3).text());
                item['productName'] = $.trim($tr1.find('td').eq(4).text());
                item['colourId'] = $.trim($tr1.find('td').eq(5).attr("_mash_colour_id"));
                item['suitSizeName'] = $.trim($tr1.find('td').eq(6).text());
                item['inBox'] = $.trim($tr1.find('td').eq(7).text());
                item['inCase'] = $.trim($tr1.find('td').eq(8).text());
                item['shippingMarkNo'] = $.trim($tr1.find('td').eq(9).text()) === "" ? null : $.trim($tr1.find('td').eq(9).text());
                item['description'] = $.trim($tr1.find('td').eq(10).text()) === "" ? null : $.trim($tr1.find('td').eq(10).text());
                item['createdBy'] = $("#UserId").val();
                item['updatedBy'] = $("#UserId").val();
                if (parseInt($tr1.attr("_mash_id")) === 0) {
                    insertList.push(item);
                } else {
                    updateList.push(item);
                }
            }
        });
        jsonResult["insertList"] = insertList;
        jsonResult["updateList"] = updateList;
        return JSON.stringify(jsonResult);
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        super.SaveLines("/trade/packing_list/lines/save.html", function (data, $self) {
            if (data.LinesList !== undefined) {
                // 刷新明细
                $self.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel("保存成功。");
            }
        });
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = $("#HeaderId").val();
        params['LinesId'] = $self.parent().parent().attr("mash_id");
        params['LinesData'] = "单据号：" + $("#BillNo").val() +
                "　起始箱号：" + $self.parent().parent().find("td").eq(1).text() + "-" + $self.parent().parent().find("td").eq(2).text() +
                "　款号：" + $self.parent().parent().find("td").eq(3).text() +
                "　颜色：" + $self.parent().parent().find("td").eq(5).text() +
                "　尺码：" + $self.parent().parent().find("td").eq(6).text();
        params['DeletedBy'] = $.trim($("#UserId").val());
        super.DeleteLines(params, "/trade/packing_list/lines/delete.html", function (data, $self) {
            // 刷新明细
            $self.BuildDataTable(data.LinesList);

            ShowSuccessMessagePanel("删除成功。");
        });
    }
    BatchDeleteLines() {
        if ($('#tabData31 tbody').find("tr.row__selected").length === 0) {
            ShowErrorMessagePanel("请选择批量删除的记录。");
            return false;
        }
        super.BatchDeleteLines('/trade/packing_list/lines/batchdelete.html', function (data, $self) {
            // 刷新本次发货生产情况
            //_InstancePageLinesMo.BuildDataTable(data.LinesMoList);
            // 刷新合同明细
            $self.BuildDataTable(data.LinesList);

            ShowSuccessMessagePanel("删除成功。");
            $("#CheckAll").prop("checked", false);
        });
    }
    InsertNewRow() {
        let $newLine_01 = $('<tr class="newLine" _mash_id="0" style=" border-top:1px solid #c6c3bd;">' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.RemoveNewRow($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td>' + $("#StyleNo").val() + '</td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell" _mash_colour_id="0"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell">' + $("#InCase").val() + '</td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');

        $('#tabData31 tbody').append($newLine_01);   // 加在后面

        let id = "_cell__field";
        let name = "__cell__field";
        let _this = this;
        $newLine_01.find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 5:
                    OnCellPopupEditEvent($(this), id, name, ($input) => {
                        _this.DoChoiceColour($input);
                    });
                    OnCellPopupEditEvent($(this), id, name, this.DoChoiceColour);
                    break;
                default:
                    OnCellClickEvent($(this), id, name, 0);
                    break;
            }
        });

        setOneTableRowColor("tabData31");
        this.rows = this.rows + 1;
    }
    RemoveNewRow($self) {
        showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', () => {
            $self.parent().parent().remove();
            setOneTableRowColor("tabData31");

            this._rows = this._rows - 1;
            // 设置明细部分高度
            this.AutoAdjustTableHeightForLines();
        });
    }
    // 弹出颜色的选择窗口
    DoChoiceColour($input) {
        this.$input = $input;
        let _choice = new CommonChoice();
        _choice.DoChoiceColour(0, (data) => {
            if (data === false) {
                this.$input.focus();
            } else {
                this.$input.parent().attr("_mash_colour_id", data[0]);
                this.$input.val(data[2]);   // 色号
                this.$input.focus();
            }
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function () {}, function () {});
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = 214;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        //$(document.body).append('<div id="test" style="background:red;width:100%;position:absolute; top:' + _tabTop + 'px;display:block;height:5px;z-index:10000" />');
        let _rc = Math.floor((h - _tabTop - 25) / 25);
        let _dh = _rc * 25;
        let _rowH = this.rows * 25; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD31").css({"max-height": _dh, height: _dh});
    }
}

let _InstancePageHeader = null;
let _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let packing_list_list_result = $.cookie("packing_list_list_result") === undefined ? "" : $.cookie("packing_list_list_result");
    let _pageListData = [];
    if (packing_list_list_result !== "") {
        _pageListData = packing_list_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/trade/packing_list/list.html",
            "/trade/packing_list/header/fetchByKey.html",
            "/trade/packing_list/header/save.html",
            "/trade/packing_list/header/export.html",
            "/trade/packing_list/header/print.html");

    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    window.laydate.render({
        elem: '#DateOfSigning',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#DateOfArrival',
        theme: '#393D49',
        trigger: 'click'
    });

    //_InstancePageHeader.OnPageLoad();
    $("#loading").hide();
}

// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();
    let wLeftList = 383;
    
    $("#divH12").css({left: 0, width: w - 16 - wLeftList});
    $("#divD12").css({left: -1, width: w - 15 - wLeftList});
    
    if (_InstancePageLines !== null)
        _InstancePageLines.AutoAdjustTableHeightForLines();
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _BillNo: "required",
            _DoBillNo: "required",
            _GarmentFactoryName: "required",
            _InCase: "required"
        },
        messages: {
            _BillNo: "请填写外贸箱单号。",
            _DoBillNo: "请选择发货发令单号。",
            _GarmentFactoryName: "请填写加工厂。",
            _InCase: "请填写箱装。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

// 验证输入
function CheckGridInput() {
    $('#tabData31 tbody').find("tr").each(function (index) {
        let $tr1 = $(this);
        let _startNo = $.trim($tr1.find('td').eq(2).text()) === '' ? 0 : $.trim($tr1.find('td').eq(1).text()); // 
        let _endNo = $.trim($tr1.find('td').eq(3).text()) === '' ? 0 : $.trim($tr1.find('td').eq(2).text());   //         
        //   let _noOfStyle = $.trim($tr1.find('td').eq(4).text());
        let _productName = $.trim($tr1.find('td').eq(4).text());
        let _colourId = $.trim($tr1.find('td').eq(5).attr("_mash_colour_id"));
        let _sizeName = $.trim($tr1.find('td').eq(6).text());
        let _quantityInBox = $.trim($tr1.find('td').eq(7).text()) === '' ? 0 : $.trim($tr1.find('td').eq(8).text()); // 
        let _inCase = $.trim($tr1.find('td').eq(8).text()) === '' ? 0 : $.trim($tr1.find('td').eq(9).text()); //   
        if (_startNo !== 0) {
            if (!isNumber(_startNo)) {
                GridCheckErrHandle($tr1, 1, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 1);
            }
        } else {
            GridCheckErrHandle($tr1, 1, '请输入起始箱号。');
        }
        if (_endNo !== 0) {
            if (!isNumber(_endNo)) {
                GridCheckErrHandle($tr1, 2, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 2);
            }
        } else {
            GridCheckErrHandle($tr1, 2, '请输入结束箱号。');
        }
        if (_quantityInBox !== 0) {
            if (!isNumber(_quantityInBox)) {
                GridCheckErrHandle($tr1, 7, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 7);
            }
        } else {
            GridCheckErrHandle($tr1, 7, '请输入箱内数量。');
        }
        if (_inCase !== 0) {
            if (!isNumber(_inCase)) {
                GridCheckErrHandle($tr1, 8, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr1, 8);
            }
        } else {
            GridCheckErrHandle($tr1, 8, '请输入箱装。');
        }
        if (_productName === "") {
            GridCheckErrHandle($tr1, 8, '请输入品名。');
        } else {
            GridCheckSuccessHandle($tr1, 8);
        }
        if (_colourId === "0") {
            GridCheckErrHandle($tr1, 8, '请输入颜色。');
        } else {
            GridCheckSuccessHandle($tr1, 8);
        }
        if (_sizeName === "") {
            GridCheckErrHandle($tr1, 6, '请输入尺码。');
        } else {
            GridCheckSuccessHandle($tr1, 6);
        }
    });
    if ($('#tabData31 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}